/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package checksummd5;

/**
 *
 * @author Minh
 */
import java.security.*;
import java.io.*;
import java.util.zip.Checksum;

public class CheckSumMD5 {

public static long calculateChecksum(byte[] buf) {
    int length = buf.length;
    int i = 0;

    long sum = 0;
    long data;

    // Handle all pairs
    while (length > 1) {
      // Corrected to include @Andy's edits and various comments on Stack Overflow
      data = (((buf[i] << 8) & 0xFF00) | ((buf[i + 1]) & 0xFF));
      sum += data;
      // 1's complement carry bit correction in 16-bits (detecting sign extension)
      if ((sum & 0xFFFF0000) > 0) {
        sum = sum & 0xFFFF;
        sum += 1;
      }

      i += 2;
      length -= 2;
    }

    // Handle remaining byte in odd length buffers
    if (length > 0) {
      // Corrected to include @Andy's edits and various comments on Stack Overflow
      sum += (buf[i] << 8 & 0xFF00);
      // 1's complement carry bit correction in 16-bits (detecting sign extension)
      if ((sum & 0xFFFF0000) > 0) {
        sum = sum & 0xFFFF;
        sum += 1;
      }
    }

    // Final 1's complement value correction to 16-bits
    sum = ~sum;
    sum = sum & 0xFFFF;
    return sum;

  }

public static long checksum(byte[] buf, int length) {
    int i = 0;
    long sum = 0;
    while (length > 0) {
        sum += (buf[i++]&0xff) << 8;
        if ((--length)==0) break;
        sum += (buf[i++]&0xff);
        --length;
    }

    return (~((sum & 0xFFFF)+(sum >> 16)))&0xFFFF;
}
public static void main(String[] args)
{
    byte[] buf= new byte[100];
    for(int i=0;i<100;i++)
    {
        buf[i]=(byte) i;
    }
    long create=calculateChecksum(buf);
    long kq=checksum(buf,50);
    if(create==kq)
    {
        System.out.print(kq);
    System.out.print("same");
    }
    else
    {
          System.out.println(kq);
            System.out.println(create);
        System.out.println("dif");
    }
}

 
}
